package nl.saxion.webtech.roulette.model;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;

import javax.swing.Timer;

public class Table {
	private static final int	MAX_PLAYER_AMOUNT	= 10;

	private int					tableId;
	private ArrayList<Player>	players;
	private ArrayList<Bet>		bets;

	public Table( int tableId ) {
		this.players = new ArrayList<Player>();
		this.bets = new ArrayList<Bet>();
		this.tableId = tableId;
		
		playGame();
	}
	
	public void playGame() {
		int betDelay = 10000; // 10 seconds
		
		//start timer! || Better to start a new thread?
		ActionListener performTask = new ActionListener() {
			@Override
			public void actionPerformed( ActionEvent e ) {
				boolean isBlack = Math.random() > 0.50;
				for( Bet b : bets ) {
					if( b.getIsBlack() == isBlack ) {
						for( Player p : players ) {
							if( p.getPlayerId() == b.getPlayerId() ) {
								p.addCash( b.getCashAmount() * 2 );
							}
						}
					}
				}
				bets.clear();
			}
		};
		new Timer( betDelay, performTask ).start(); 
	}

	public int getBetAmount( int playerId ) {
		for( Bet bet : bets ) {
			if( bet.getPlayerId() == playerId ) {
				return (int)bet.getCashAmount();
			}
		}
		return 0;
	}

	public boolean userBoughtInCash( int playerId, int cash ) {
		Player player = getPlayer( playerId );
		int totalCash = player.getAmountOfCash();
		if( totalCash < cash ) {
			return false;
		} else {
			player.setAmountOfCash( totalCash - cash );
			return true;
		}
	}

	private Player getPlayer( int playerId ) {
		for( Player player : players ) {
			 if(player.getPlayerId() == playerId){
				 return player;
			 }
		}
		return null;
	}

	public int getTableId() {
		return tableId;
	}

	public ArrayList<Player> getPlayers() {
		return players;
	}

	public boolean addPlayer( Player player ) {
		if( !checkIfFull( players.size() ) ) {
			players.add( player );
			return true;
		} else {
			System.out.println( "The table is currently full" );
			return false;
		}
	}

	public boolean removePlayer( int playerId ) {
		for( Player player : players ) {
			 if(player.getPlayerId() == playerId){
				 players.remove(player);
				 return true;
			 }
		}
		return false;
	}

	private boolean checkIfFull( int amountOfPlayers ) {
		if( amountOfPlayers == MAX_PLAYER_AMOUNT ) {
			return true;
		} else
			return false;
	}

	public boolean placeBet( Bet bet ) {
		bets.add( bet );
		return false;
	}

	public ArrayList<Bet> getBets() {
		return bets;
	}
}